//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using EffiProzDB.Lib;
using EffiProzDB.DataTypes;

namespace EffiProzDB.RowIO
{
    /**
     * Base class for writing the data for a database row _in different formats.
     * Defines the methods that are independent of storage format and declares
     * the format-dependent methods that subclasses should define.
     *
     * @author sqlbob@users (RMP)
     * @author fredt@users
     * @version 1.7.2
     * @since 1.7.0
     */
    public abstract class RowOutputBase : HsqlByteArrayOutputStream
    , RowOutputInterface
    {

        public  const int CACHED_ROW_160 = 0;
        public  const int CACHED_ROW_170 = 1;

        // the last column _in a table is an ID that should not be written to file
        protected bool skipSystemId = false;

        /**
         *  Constructor used for persistent storage of a Table row
         *
         * @exception  IOException when an IO error is encountered
         */
        public RowOutputBase()
            : base()
        {

        }

        /**
         *  Constructor used for result sets
         *
         * @exception  IOException when an IO error is encountered
         */
        public RowOutputBase(int initialSize)
            : base(initialSize)
        {

        }

        /**
         *  Constructor used for network transmission of result sets
         *
         * @exception  IOException when an IO error is encountered
         */
        public RowOutputBase(byte[] buffer)
            : base(buffer)
        {

        }

        // fredt@users - comment - methods for writing Result column type, name and data size
        public abstract void writeEnd();

        public abstract void writeSize(int size);

        public abstract void writeType(int type);

        public abstract void writeShortData(short i);

        public abstract void writeIntData(int i);

        public abstract void writeIntData(int i, int position);

        public abstract void writeString(string s);

        // fredt@users - comment - methods used for writing each SQL type
        protected virtual void writeFieldPrefix() { }

        protected abstract void writeFieldType(int type);

        protected abstract void writeNull(int type);

        protected abstract void writeChar(string s, int t);

        protected abstract void writeSmallint(short o);

        protected abstract void writeInteger(int o);

        protected abstract void writeBigint(long o);

        protected abstract void writeReal(Double o, int type);

        protected new  abstract void writeDecimal(Decimal o);

        protected abstract void writeBit(bool o);

        protected abstract void writeDate(DateTime o);

        protected abstract void writeTime(DateTime o);

        protected abstract void writeTimestamp(DateTime o);

        protected abstract void writeOther(DotNetObject o);

        protected abstract void writeBinary(Binary o, int t);

        public abstract int getSize(CachedRow row);

        public abstract void writeLongData(long i);

        public void writeRow(Object[] data, Table t)
        {

            writeSize(0);
            writeData(data, t);
            writeIntData(size(), 0);
        }

        /**
         *  This method is called to write data for a table.
         *
         * @param  data
         * @param  t
         * @throws  IOException
         */
        public void writeData(Object[] data, Table t)
        {

            int[] types = t.getColumnTypes();
            int l = t.getColumnCount();

            writeData(l, types, data, null, null);
        }

        /**
         *  This method is called to write data for a Result.
         *
         * @param  l
         * @param  types
         * @param  data
         * @param cols
         * @param primarykeys
         * @throws  IOException
         */
        public void writeData(int l, int[] types, Object[] data,
                              IList<Column> cols, int[] primaryKeys)
        {

            bool hasPK = primaryKeys != null && primaryKeys.Length != 0;
            int limit = hasPK ? primaryKeys.Length
                                  : l;

            for (int i = 0; i < limit; i++)
            {
                int j = hasPK ? primaryKeys[i]
                                 : i;
                Object o = data[j];
                int t = types[j];

                if (cols != null)
                {
                    Column col = (Column)cols[j];

                    writeFieldPrefix();
                    writeString(col.columnName.statementName);
                }

                if (o == null)
                {
                    writeNull(t);

                    continue;
                }

                writeFieldType(t);

                switch (t)
                {

                    case Types.NULL:
                    case Types.CHAR:
                    case Types.VARCHAR:
                    case Types.VARCHAR_IGNORECASE:
                    case Types.LONGVARCHAR:
                        writeChar(Convert.ToString(o), t);
                        break;

                    case Types.TINYINT:
                    case Types.SMALLINT:
                        writeSmallint(Convert.ToInt16(o));
                        break;

                    case Types.INTEGER:
                        writeInteger(Convert.ToInt32(o));
                        break;

                    case Types.BIGINT:
                        writeBigint(Convert.ToInt64(o));
                        break;

                    case Types.REAL:
                    case Types.FLOAT:
                    case Types.DOUBLE:
                        writeReal(Convert.ToDouble(o), t);
                        break;

                    case Types.NUMERIC:
                    case Types.DECIMAL:
                        writeDecimal(Convert.ToDecimal(o));
                        break;

                    case Types.BOOLEAN:
                        writeBit(Convert.ToBoolean(o));
                        break;

                    case Types.DATE:
                        writeDate(Convert.ToDateTime(o));
                        break;

                    case Types.TIME:
                        writeTime(Convert.ToDateTime(o));
                        break;

                    case Types.TIMESTAMP:
                        writeTimestamp(Convert.ToDateTime(o));
                        break;

                    case Types.OTHER:
                        writeOther((DotNetObject)o);
                        break;

                    case Types.BINARY:
                    case Types.VARBINARY:
                    case Types.LONGVARBINARY:
                        writeBinary((Binary)o, t);
                        break;

                    default:
                        throw Trace.runtimeError(Trace.FUNCTION_NOT_SUPPORTED,
                                                 Types.getTypeString(t));
                }
            }
        }

        // returns the underlying HsqlByteArrayOutputStream
        public HsqlByteArrayOutputStream getOutputStream()
        {
            return this;
        }
    }
}
